/**
 *表格类 
 *基于oacore
 */
(function () {
	/**
	 * action: 'ACTIONS'配置的名称
	 * tableUI: 表格ui名称
	 * advancedSearchUI: 高级搜索ui
	 * openAdvancedSearchWidget: 高级搜索打开控件
	 * parent: 表格父元素
	 * callback: 表格刷新后的回调函数
	 * advUICallback: 高级搜索弹出后的回调函数
	 * tableInitData: 每次渲染表格时传给其的初始化数据
	 * advInitData: 高级搜索的初始化数据
	 * advProxy: 设置高级搜索的代理，作用为自定义一个搜索方法，返回false不执行默认搜索方法,会传递序列化后的搜索参数
	 * pageProxy: 设置翻页回调函数，会把当前页数当做参数传给回调方法,返回false不执行默认翻页方法
	 * sortProxy: 设置排序回调函数，会吧当前排序的字段，排序方式传给回调方法，返回false不执行默认排序方法
	 * pageSize: 页大小
	 * initCallback: 表格对象初始化完成时调用的方法
	 * templateIncludes: 包含的模板(数组形式)
	 * requestPageParams: 请求页附加的参数
	 * filterData: 过滤html
	 */
	function Table(params)
	{
		this.action = params.action;
		var topHost = this;
		this.filter;
		this.pageProxy = params.pageProxy;
		this.sortProxy = params.sortProxy;
		this.thSortState= {
			fieldName: "",
			method: ""
		};
		var parent = $(params.parent);
		//添加附加参数
		if(params.action.url.search(/\?/) == -1)
			params.action.url += "?" + params.requestPageParams;
		else
		{
			params.action.url += "&" + params.requestPageParams;
		}
		//初始化翻页组件
		this.table = new $.util.view.Paging({
			pageSizeJsonName: params.action.data.PAGE_SIZE,
			recordCountJsonName: params.action.data.RECORD_COUNT,
			postPageName: params.action.params.PAGE,
			postPageSizeName: params.action.params.PAGE_SIZE,
			pageSize: params.pageSize,
			requestMethod : params.requestMethod,
			success: function (data) {
				return true;
			},
			updateMethod: function (data) {
				var host = this;
				//初始化表格UI
				parent.empty();
				if(params.tableInitData)
					$.extend(data, params.tableInitData);
				oacore.UI.render(params.tableUI, data, parent, function () {
					//获取UI成功，初始化行为。
					var pageBar = parent.find(".pagebar_area:first");
					//初始化表头排序 事件
					var lastRow, lastSortMethod;
					var th = parent.find("table:first thead:first th.data-head").each(function () {
						var rowName = /\brow-.+\b/.exec(this.className);
						if(!rowName)
							return;
						rowName = [rowName[0].split(" ")[0]];
						var sortTag = $(this).find("span.sort-tag").removeClass("tag-asc tag-desc");
						if(rowName)
							rowName = rowName[0].split('-')[1];
						else
						{
							return;
						}
						if(topHost.thSortState.fieldName != rowName)
							return;
						var sortMethod = MEM_DATA.data(rowName);
						if(sortMethod)
							sortTag.addClass("tag-" + topHost.thSortState.method.toLocaleLowerCase());
					});
					th.click(function () {
						var rowName = /\brow-.+\b/.exec(this.className);
						if(!rowName)
							return;
						rowName = [rowName[0].split(" ")[0]];
						if(rowName)
							rowName = rowName[0].split('-')[1];
						else
						{
							return;
						}
						var sortMethod = MEM_DATA.data(rowName);
						//MEM_DATA.data("clickedRowName", rowName);
						if(!sortMethod || sortMethod == "desc")
						{
							if(topHost.sortProxy)
								if(topHost.sortProxy(rowName, "asc") == false)
									return false;
							topHost.sort(rowName, "asc");
						}
						else
						{
							if(topHost.sortProxy)
								if(topHost.sortProxy(rowName, "desc") == false)
									return false;
							topHost.sort(rowName, "desc");
						}
					});
					//初始化分页条UI
					oacore.UI.render("table/pageBar/pageBar", host.pageInfo, pageBar, function () {
						//初始化分页条的事件
						pageBar.find(".pageJump:first").click(function () {
							var page = parseInt(pageBar.find(".currentPage:first").val());
							if(topHost.pageProxy)
								if(topHost.pageProxy(page) == false)
									return false;
							topHost.setPage(page);
						});
						pageBar.find(".jumpToFirst:first").click(function () {
							if(topHost.pageProxy)
								if(topHost.pageProxy(topHost.table.pageInfo.firstPage()) == false)
									return false;
							topHost.firstPage();
						});
						pageBar.find(".jumpToLast:first").click(function () {
							if(topHost.pageProxy)
								if(topHost.pageProxy(topHost.table.pageInfo.lastPage()) == false)
									return false;
							topHost.lastPage();
						});
						topHost.outputPaging(7, pageBar.find(".pagTags:first"));
					});
					parent.find("th.data-head").hover(
							function () {
								var selected = $(this).addClass("dh-selected");
								var tagDesc = selected.find("span.tag-desc");
								tagDesc.addClass("tag-desc-highlight");
								if(tagDesc.size() > 0)
									return;
								var tagAsc = selected.find("span.tag-asc");
								tagAsc.addClass("tag-asc-highlight");
								if(tagAsc.size() > 0)
									return;
								selected.find("span.sort-tag").addClass("sort-cue");
							},
							function () {
								var selected = $(this).removeClass("dh-selected");
								var tagDesc = selected.find("span.tag-desc");
								tagDesc.removeClass("tag-desc-highlight");
								if(tagDesc.size() > 0)
									return;
								var tagAsc = selected.find("span.tag-asc");
								tagAsc.removeClass("tag-asc-highlight");
								if(tagAsc.size() > 0)
									return;
								selected.find("span.sort-tag").removeClass("sort-cue");
							});
					if(params.callback)
						params.callback();
				}, {includes: params.templateIncludes, filter_data: params.filterData == false ? false : true});
			}
		});
		var postParams = {};
		//postParams[params.action.params.SORT] = null;
		//postParams[params.action.params.SORT_METHOD] = null;
		postParams["orderConditions[0].propertyName"] = "";
		postParams["orderConditions[0].order"] = "";
		postParams["orderConditions[1].propertyName"] = "";
		postParams["orderConditions[1].order"] = "";
		this.table.createAction("list", {
				url: params.action.url,
				params: postParams
			});
		postParams = {};
		//postParams[params.action.params.SORT] = null;
		//postParams[params.action.params.SORT_METHOD] = null;
		postParams[params.action.params.SEARCH] = null;
		postParams[params.action.params.ADVANCED] = false;
		postParams["orderConditions[0].propertyName"] = "";
		postParams["orderConditions[0].order"] = "";
		postParams["orderConditions[1].propertyName"] = "";
		postParams["orderConditions[1].order"] = "";
		this.table.createAction("search", {
				url: params.action.url,
				params: postParams
			});
		this.table.transform("list");
		this.isShow = false;
		this.box = new oacore.UI.FloatBox({});
		this.box.onHide = function () {
			topHost.isShow = false;
		};
		$(params.openAdvancedSearchWidget).unbind("click").click(function () {
			if(topHost.isShow)
				return false;
			topHost.isShow = true;
			var $this = $(this);
			if(topHost.init)
			{
				var pos = $this.offset();
				topHost.box.show();
				topHost.box.content.offset({left: 0, top: 0}).offset({left: pos.left - topHost.box.content.width() + $this.width(), top: pos.top + $this.height()});
				return false;
			}
			oacore.UI.render(params.advancedSearchUI, params.advInitData, topHost.box.content, function () {
					topHost.box.content.appendTo(document.body);
					topHost.box.content.find(".startAdvSearch:first").click(function () {
						//序列化高级搜索form的数据.并将其传给高级搜索.
						var serizlize = topHost.box.content.find("form:first").formSerialize();
						if(params.advProxy)
							if(params.advProxy(serizlize) == false)
							{
								topHost.box.hide();
								return false;
							}
						topHost.advSearch(serizlize);
						topHost.box.hide();
						return false;
					});
					topHost.box.content.find(".advanced-close:first").click(function () {
						topHost.box.hide();
						return false;
					});
					function adjust() {
						var pos = $this.offset();
						topHost.box.content.offset({left: 0, top: 0})
						.css({left: pos.left - topHost.box.content.width() + $this.width(), top: pos.top + $this.height()});
					};
					adjust();
					$(window).bind("scroll resize", adjust);
					if(params.advUICallback)
						params.advUICallback.apply(topHost.box.content);
					topHost.init = true;
				});
			return false;
		});
	};
	
	Table.prototype.nextPage = function () {
		this.table.nextPage();
	};
	
	Table.prototype.prevPage = function () {
		this.table.prevPage();
	};
	
	Table.prototype.setPage = function (page) {
		this.table.setPage(page);
	};
	
	Table.prototype.firstPage = function () {
		this.table.firstPage();
	};
	
	Table.prototype.lastPage = function () {
		this.table.lastPage();
	};
	
	Table.prototype.onActionChange = function () {
		
	};
	
	Table.prototype.list = function () {
		if(this.onActionChange)
			this.onActionChange();
		this.table.transform("list");
	};
	
	Table.prototype.search = function (value) {
		if(this.onActionChange)
			this.onActionChange();
		this.table.transform("search");
		this.table.setParam(this.action.params.SEARCH, $.trim(value));
		this.table.addParams(this.initParams);
	};
	
	function pushValueToParams(params, name, value) {
		if(params[name])
			params[name].push(value);
		else
		{
			params[name] = [value];
		}
	};
	
	/**
	 * 将参数转换为"PropertyFilter"格式
	 * @param values
	 * @return
	 */
	Table.toPF = function (values) {
		values = decodeURIComponent(values);
		var params = values.split("&");
		var paramsMap = {};
		var finalParamsStr = [];
		//把参数序列整理为对象形式
		for(var i=0;i<params.length;++i)
		{
			var param = params[i].split("=");
			pushValueToParams(paramsMap, param[0], $.trim(param[1]).replace(/\+/g, " "));
		}
		//PropertyFilters下标
		var index = 0;
		for(var name in paramsMap)
		{
			var paramType = name.split("$")[1];
			//var paramDataType = name.split("#")[1].toUpperCase() || "STRING"; 
			//paramDataType赋一个初值,如果没有定义的话 就赋成STRING 
			var paramDataType;
			if (name.split("#")[1]) {
				paramDataType= name.split("#")[1].toUpperCase();
			}else{
				paramDataType="STRING";
			}
			var paramValues = paramsMap[name];
			var paramName = name.split("$")[0].split("#")[0];
			//生成不同的参数格式
			switch(paramType)
			{
			case "normal":	//一般方式
				if(paramValues.length > 0)
					finalParamsStr.push(paramName + "=" + paramValues.join("&" + paramName + "=") + "&");
				break;
			default:	//默认为用PropertyFilter包装
				//参数个数大于零的时候执行包装
				if(paramValues.length > 0)
				{
					//默认操作LIKE
					var operation;
					if(paramDataType != "STRING")
						operation = "EQ";
					else
					{
						operation = "LIKE";
					}
					//两个参数则进行区间处理:"between" || "ge" || "le"
					if(paramValues.length == 2)
					{
						if(paramValues[0] && paramValues[0].length > 0)
							operation = "GE";
						if(paramValues[1] && paramValues[1].length > 0)
						{
							if(operation == "GE")
								operation = "BETWEEN";
							else
							{
								operation = "LE";
							}
						}
					}
					if(paramValues[0] || paramValues[1])
					{
						finalParamsStr.push("propertyFilters[" + index + "].propertyName=" + paramName + "&");	
						if(paramValues[0])
						{
							finalParamsStr.push("propertyFilters[" + index + "].propertyValueStr=" + paramValues[0] + "&");	
							if(paramValues[1])
								finalParamsStr.push("propertyFilters[" + index + "].propertyValue1Str=" + paramValues[1] + "&");	
						}else if(paramValues[1])
						{
							finalParamsStr.push("propertyFilters[" + index + "].propertyValueStr=" + paramValues[1] + "&");	
						}
						finalParamsStr.push("propertyFilters[" + index + "].operator=" + operation + "&");
						finalParamsStr.push("propertyFilters[" + index + "].propertyValueType=" + paramDataType + "&");
						++ index;
					}
				}
				break;
			}
		}
		finalParamsStr = finalParamsStr.join("");
		var andIndex = finalParamsStr.lastIndexOf("&");
		//清除最后一个"&"
		if(andIndex != -1)
			finalParamsStr = finalParamsStr.substring(0, andIndex);
		return finalParamsStr;
	};
	
	Table.prototype.advSearch = function (values) {
		if(this.onActionChange)
			this.onActionChange();
		var postParams = {};
		var host = this;
		//
		values = Table.toPF(values);
		//
		postParams[this.action.params.ADVANCED] = true;
		$.extend(postParams, $.util.paramsToObj(values));
		$.extend(postParams, this.initParams);
		this.table.createAction("advanced", {
				url: host.action.url,
				params: postParams
			});
		this.table.transform("advanced");
	};
	
	Table.prototype.resetTable = function () {
		this.table.resetAllParam();
	};
	
	Table.prototype.cleanSortEffect = function () {
		this.thSortState = {
			fieldName: "",
			method: ""
		};
	};
	
	Table.prototype.filterResults = function (filter) {
		if(this.filter)
		{
			var parsedFilter = this.filter.split("&");
			for(var i=0;i<parsedFilter.length;++i)
				this.table.deleteParam(parsedFilter[i].split("=")[0]);
		}
		if(filter != null)
		{
			this.filter = filter;
			this.table.addParams(filter);
		}
	};
	
	Table.prototype.sort = function (field, method) {
		MEM_DATA.data(field, method);
		
		//Modified by Rxh 2011-01-10
		var params = this.getParams();
		params = $.util.paramsToObj(params);
		
		var oldField = params["orderConditions%5B0%5D.propertyName"];
		var oldMethod = params["orderConditions%5B0%5D.order"];
		
		if (oldField != null && oldMethod != null
				&& oldField != field){
			//再生成一个OrderCondition对象.
			this.table.addParams({
				"orderConditions[1].propertyName" : oldField,
				"orderConditions[1].order" : oldMethod
			});
		}
		//再生成一个OrderCondition对象.
		this.table.addParams({
			"orderConditions[0].propertyName" : field,
			"orderConditions[0].order" : method
		});
	};
	
	Table.prototype.sort1 = function (field, method) {
		MEM_DATA.data(field, method);
		this.thSortState = {
			fieldName: field,
			method: method
		};
		this.table.setParam("orderConditions[0].propertyName", field);
		this.table.setParam("orderConditions[0].order", method);
	};
	
	Table.prototype.sort2 = function (field, method) {
		MEM_DATA.data(field, method);
		this.thSortState = {
				fieldName: field,
				method: method
			};
		this.table.setParam("orderConditions[1].propertyName", field);
		this.table.setParam("orderConditions[1].order", method);
	};
	
	Table.prototype.getParams = function () {
		return $.param(this.table.getCurAction().params);
	};
	
	Table.prototype.outputPaging = function (size, parent) 
	{
		var pageInfo = this.table.pageInfo;
		var host = this;
		var content = $("<div>");
		if(pageInfo.currentPage > 1)
			content.html("<button class='prevPageBtn special prev-page'><span></span></button>");
		var startPage = pageInfo.currentPage;
		var loopCount = parseInt( size / 2 );
		if(loopCount == size / 2)
			-- loopCount;
		pageInfo.currentPage *= 1;
		var leftInc = pageInfo.currentPage + loopCount - pageInfo.maxPage;
		if(leftInc > 0)
			loopCount += leftInc;
		for(var i=0;i<loopCount;++i)
		{
			if(startPage <= 1)
				break;
			-- startPage;
		}
		for(var i=0;i<size;++i)
		{
			if(startPage != pageInfo.currentPage)
				content.append("<a class='pageTag " + startPage + "_Page page-tag' href='javascript:void(0);'>" + startPage + "</a>");
			else
			{
				content.append("<a class='page-tag pageTag pt-selected " + startPage + "_Page' href='javascript:void(0);'>" + startPage + "</a>");
			}
			if(++ startPage > pageInfo.maxPage)
				break;
		}
		if(pageInfo.currentPage < pageInfo.maxPage)
			content.append("<button class='nextPageBtn special next-page'><span></span></button>");
		content.find("a.pageTag").click(function () {
			var page = /\b[\d]+_Page\b/.exec(this.className);
			if(host.pageProxy)
				if(host.pageProxy(parseInt(page[0])) == false)
					return false;
			if(page)
				host.setPage(parseInt(page[0]));
		});
		content.find("button.prevPageBtn:first").click(function () {
			if(host.pageProxy)
				if(host.pageProxy(host.table.pageInfo.prevPage()) == false)
					return false;
			host.prevPage();
		});
		content.find("button.nextPageBtn:first").click(function () {
			if(host.pageProxy)
				if(host.pageProxy(host.table.pageInfo.nextPage()) == false)
					return false;
			host.nextPage();
		});
		$(parent).append(content.children());
	};
	
	oacore.UI.Table = Table;
	
	var MEM_DATA = $({});
})();